from machine import Pin, ADC
import time

#定义27是光敏传感器，要变成模拟的，使用ADC转换
guangmin = ADC(Pin(15))
guangmin.atten(ADC.ATTN_11DB)  #给出一个电压的值

#定义两个按钮（使用中断）
btn1 = Pin(12,Pin.IN,Pin.PULL_UP) #增加阈值
btn2 = Pin(14,Pin.IN,Pin.PULL_UP) #减少阈值

# 定义26是LED灯
led = Pin(23, Pin.OUT)

# 初始阈值
threshold = 4000
# 阈值变化步长
step = 100

def adjust_threshold(pin):
    global threshold
    if pin == btn1:
        # 按钮1按下，增加阈值
        threshold += step
    elif pin == btn2:
        # 按钮2按下，减少阈值
        threshold = max(0, threshold - step)  # 确保不小于0
    print("New threshold:", threshold)


#设置中断
btn1.irq(trigger=Pin.IRQ_FALLING,handler=adjust_threshold)
btn2.irq(trigger=Pin.IRQ_FALLING,handler=adjust_threshold)  


if __name__ == "__main__":
    #这块是主程序，相当于c中的main()
    
    # 初始化
    led.value(0)
    
    while True:
        # 读取光敏值
        light_value = guangmin.read()
        print("Light:", light_value, "| Threshold:", threshold)
        
        # 控制LED
        if light_value > threshold:
            led.value(1)
        else:
            led.value(0)
            
        time.sleep(0.5)